import {
		addShoppingCart,
		removeShoppingCart,
	} from "@/request/api.js";
import util from "@/utils/util.js"
export default {
	mounted() {
		// window.addEventListener("scroll", this.handleScroll, true);

	},
	methods: {
		
		// 获取购物车信息
		getShopCar() {
			this.$refs.shopCar.getShopCar();
		},
		
		//购物车操作
		 //展示列表的购物车加减以及规格弹窗的添加至购物车
		 async changeShopNum(type, foodItem, item,addressId,addType = 'shopCar') {
			 
			 // if(addType == 'createOrder' && foodItem.count == 1 && type == 'down'){
			 // 	uni.showToast({
			 // 		title:"最少点一份，如需删除，请返回一页面操作!",
			 // 		icon:'none'
			 // 	})
				// return;
			 // }
			 // 
			 //  let mustSelectedFoodsStorage = uni.getStorageSync("mustSelectedFoodsStorage")
			 // if(addType == 'createOrder' && foodItem.count == 1 && type == 'down' && mustSelectedFoodsStorage){
				// 	let newStore = JSON.parse(mustSelectedFoodsStorage)?.find(item=>item.storeId == foodItem.storeId)
				// 	if(newStore){
				// 		// let newFood = this.shopCarInfo.shopCarList.filter(item=>item.storeId == newStore.storeId);
				// 		let foodIndex = newStore?.mustSelectedFoods.findIndex(item=>item == foodItem.foodId);
				// 		if(foodIndex != -1){
				// 			uni.showToast({
				// 				title:`${foodItem.foodName}是必点菜品，最少点一份!`,
				// 				icon: 'none',
				// 				duration:3000
				// 			})
				// 			return;
				// 		}
				// 	}
			 // }
		 	let token = uni.getStorageSync('token');
			let userInfo = uni.getStorageSync('userInfo');
		 	// 没有登录，显示登录弹窗
		 	if (!token){
				this.auth = true;
				return;
			}
		 	if (type == 'add') {
		 		if (foodItem.limitCount < 1) {
		 			this.$showToast(this, '库存不足，无法继续添加', 'fail');
		 			return;
		 		}
				 // "phone":"13751941714"
				 // ,    "menuId":"c752804d0cd410267f404dd3f0412346",   
				 //  "storeId":"d046cfb267fb7efeacc8967575ffcc6c",    
				 // "foodId":"2aaf5b6594fcf6b455a37ee8d758da00",    "count":1,   
				 //  "specification":"[]"
				 console.log(userInfo,"userInfo");
		 		let params = {
					"menuId":userInfo.menuId,
		 			"phone":userInfo.phoneNumber,
					// "siteAddressId": addressId,
		 			"storeId": item.storeId,
		 			// "storeName": item.storeName,
		 			"foodId": foodItem.foodId,
		 			// "foodName": foodItem.foodName,
		 			"count": 1,
		 			// "salePrice": foodItem.salePrice,
		 			"specification": foodItem.specifications
		 		}
		 		let res = await addShoppingCart({
		 			method: "POST",
		 			data: params,
		 		})
		 		if (res.code == 200) {
		 			foodItem.count += 1
		 		} else {
		 			uni.showToast({
		 				title: res.message,
		 				icon: 'none',
		 			})
		 		}
		 	} else if (type == 'down' && foodItem.count >= 1) {
		 		let res = await removeShoppingCart({
		 			method: "post",
		 			data: {
						"phone":userInfo.phoneNumber,
		 				// "siteId":addressId,
		 				"foodId": foodItem.foodId,
						"specification": foodItem.specifications ? JSON.stringify(foodItem.specifications) : [],
		 				"count": 1,
		 			},
		 		})
				if (res.code == 200) {
					foodItem.count -= 1;
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none',
					})
				}
		 	}
		 	this.getShopCar();
		 },
		
		// 设置点餐页面缓存
		setStorePage(datas){
			let storePage = uni.getStorageSync('storePage');
			let newStorePage = {};
			for(var i = 0;i <datas.length; i++){
				newStorePage[datas[i].name] = datas[i].data;
			}
			if(storePage){
				storePage = JSON.parse(storePage);
				if(datas[0]?.name == "currAddress" && storePage['currAddress'] &&  datas[0].siteId != storePage['currAddress'].siteId){
					storePage = {...newStorePage}
					console.log(1,storePage);
				}else{
					console.log(2,storePage,newStorePage);
					storePage = {...storePage,...newStorePage}
				}
			}else {
				storePage = newStorePage;
			}
			uni.setStorageSync('storePage', JSON.stringify(storePage))
		},
		// 获取点餐页面缓存
		getStorePage(){
			// let storePage = uni.getStorageSync('storePage');
			// let data = {};
			// if(storePage){
			// 	data = JSON.parse(storePage);
			// }
			// return data;
			return util.getStorePage();
		},
		
		//初始化倒计时数据
		initCountDown(type, arr) {
			this.countInfo.timer = setInterval(() => {
				if (type == 'system') {
					this.formatCountDown(type, arr);
					
				} else {
					this.shopList.forEach((item, index) => {
						this.formatCountDown(type, JSON.parse(item.businessHours), index);
						// this.fixedPriceToDiscount用来判断非企业订单的组件引用了该minix。企业订单无限时优惠。
						// 开启了限时优惠。
						if (this.fixedPriceToDiscount && item.isDiscountEnable && false) {
							let disArr = [
								{startTime: item.discountStartTime, endTime: item.discountEndTime}
							]
							this.formatCountDown('discount', disArr, index);
						}
					});
				}
			}, 1000)
		},
		//格式化倒计时数据
		formatCountDown(type, arr, index) {
			
			let nowDate = new Date();
			let year = nowDate.getFullYear();
			let month = nowDate.getMonth() + 1;
			let day = nowDate.getDate();
			let hour = nowDate.getHours();
			let minute = nowDate.getMinutes();
			let secound = nowDate.getSeconds();
			let nowTemp = nowDate.getTime();
			let dateWithFront = `${year}/${month}/${day}`

			let startTime = '',
				endTime = '';
			for (let i = 0; i < arr.length; i++) {
				let item = arr[i]
				if (item.startTime && item.endTime) {
					item.startTimeTemp = new Date(dateWithFront + ' ' + item.startTime)
						.getTime();
					item.endTimeTemp = new Date(dateWithFront + ' ' + item.endTime)
						.getTime();
					if (item.startTimeTemp > item.endTimeTemp) {
						if (nowTemp < item.startTimeTemp) {
							item.startTimeTemp = parseInt(item.endTimeTemp) - 1000 *
								60 * 60 * 24;
						} else if (nowTemp > item.endTimeTemp) {
							item.endTimeTemp = parseInt(item.endTimeTemp) + 1000 * 60 *
								60 * 24;
						}
						startTime = item.startTimeTemp;
						endTime = item.endTimeTemp;
					}
					if (nowTemp > item.startTimeTemp && nowTemp < item.endTimeTemp) {
						startTime = item.startTimeTemp;
						endTime = item.endTimeTemp;
						break;
					} else {
						startTime = '';
						endTime = '';
					}
				}
			}
			
			if (startTime && endTime) {
				this.startCountDown(type, startTime, endTime, index);
				if (type == 'discount') {
					this.fixedPriceToDiscount(index)
				}
			} else {
				if (type == 'discount') {
					let isOutDiscount = !endTime || (endTime - new Date().getTime() <= 0);
					if (isOutDiscount) {
						this.fixedPriceToOriginalPrice(index)
					}
				}
			}
		},
		//执行数据递减
		startCountDown(type, startTimeStemp, endTimeStemp, index) {
			
			let nowDateStemp = new Date().getTime();
			let oneDayStemp = 1000 * 60 * 60 * 24;
			let oneHourStemp = 1000 * 60 * 60;
			let oneMinuteStemp = 1000 * 60;
			let surplusStemp = endTimeStemp - nowDateStemp;
			let day = parseInt(surplusStemp / oneDayStemp);
			let hour = parseInt(
				(surplusStemp % oneDayStemp) / oneHourStemp
			);
			let minute = parseInt(
				((surplusStemp % oneDayStemp) % oneHourStemp) / oneMinuteStemp
			);
			let secound = parseInt(
				(((surplusStemp % oneDayStemp) % oneHourStemp) % oneMinuteStemp) /
				1000
			);

			if (hour <= 9) {
				hour = "0" + hour;
			}
			if (minute <= 9) {
				minute = "0" + minute;
			}
			if (secound <= 9) {
				secound = "0" + secound;
			}
			if (type == 'system') {
				this.countInfo.systemHour1 = Number(String(hour).split('')[0]);
				this.countInfo.systemHour2 = Number(String(hour).split('')[1]);
				this.countInfo.systemMinute1 = Number(String(minute).split('')[0]);
				this.countInfo.systemMinute2 = Number(String(minute).split('')[1]);
				this.countInfo.systemSecound1 = Number(String(secound).split('')[0]);
				this.countInfo.systemSecound2 = Number(String(secound).split('')[1]);
			} else if (type == 'discount'){
				this.countInfo[`d_day${index}`] = day;
				this.countInfo[`d_hour${index}`] = hour;
				this.countInfo[`d_minute${index}`] = minute;
				this.countInfo[`d_secound${index}`] = secound;
			} else {
				this.$set(this.countInfo,`day${index}`,day);
				this.$set(this.countInfo,`hour${index}`,hour);
				this.$set(this.countInfo,`minute${index}`,minute);
				this.$set(this.countInfo,`secound${index}`,secound);
			}
		},
		//浮点数精度问题的解决方式
		//加法
		accAdd(arg1, arg2) {
			var r1, r2, m, c;
			try {
				r1 = arg1.toString().split(".")[1].length;
			} catch (e) {
				r1 = 0;
			}
			try {
				r2 = arg2.toString().split(".")[1].length;
			} catch (e) {
				r2 = 0;
			}
			c = Math.abs(r1 - r2);
			m = Math.pow(10, Math.max(r1, r2));
			if (c > 0) {
				var cm = Math.pow(10, c);
				if (r1 > r2) {
					arg1 = Number(arg1.toString().replace(".", ""));
					arg2 = Number(arg2.toString().replace(".", "")) * cm;
				} else {
					arg1 = Number(arg1.toString().replace(".", "")) * cm;
					arg2 = Number(arg2.toString().replace(".", ""));
				}
			} else {
				arg1 = Number(arg1.toString().replace(".", ""));
				arg2 = Number(arg2.toString().replace(".", ""));
			}
			return (arg1 + arg2) / m;
		},
		//减法
		accSub(arg1, arg2) {
			var r1, r2, m, n;
			try {
				r1 = arg1.toString().split(".")[1].length;
			} catch (e) {
				r1 = 0;
			}
			try {
				r2 = arg2.toString().split(".")[1].length;
			} catch (e) {
				r2 = 0;
			}
			m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
			n = (r1 >= r2) ? r1 : r2;
			return ((arg1 * m - arg2 * m) / m).toFixed(n);
		},
		//乘法
		accMul(arg1, arg2) {
			var m = 0,
				s1 = arg1.toString(),
				s2 = arg2.toString();
			try {
				m += s1.split(".")[1].length;
			} catch (e) {}
			try {
				m += s2.split(".")[1].length;
			} catch (e) {}
			return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
		},
		//除法
		accDiv(arg1, arg2) {
			var t1 = 0,
				t2 = 0,
				r1, r2;
			try {
				t1 = arg1.toString().split(".")[1].length;
			} catch (e) {}
			try {
				t2 = arg2.toString().split(".")[1].length;
			} catch (e) {}
			r1 = Number(arg1.toString().replace(".", ""));
			r2 = Number(arg2.toString().replace(".", ""));
			return (r1 / r2) * Math.pow(10, t2 - t1);
		},
		fenToYuan: value =>{
			return parseFloat((value / 100).toFixed(2));
		},
		//h5触底加载
		handleScroll() {
			let scrollTop = document.documentElement.scrollTop; //滚动高度
			let clientHeight = document.documentElement.clientHeight; //可视高度
			let scrollHeight = document.documentElement.scrollHeight; //内容高度
			if (scrollHeight - scrollTop === clientHeight) {
				//触底加载
			}
		},

		setHidden() {
			document.body.style.overflow = 'hidden';
		},
		setAuto() {
			document.body.style = '';
		}
	}
}
